// pages/commodityMgt/index.js
import Common from '../../common/common.js';
let common = new Common;
const app = getApp() 
Page({ 
  data: {
    id: 0,
    selType: 9,
    opactive: 4,
    allproduct: [],
    items: [{
      name: '全选',
      value: '全选'
    }],
    showModal: false,
    productList: [],
    product: null, //筛选商品系列
    productType: '', //筛选库存状态//库存状态 1 售罄 2 紧张 3 充足  9全部
    productTypeList: [{
        id: 3,
        name: '库存充足'
      },
      {
        id: 2,
        name: '库存紧张'
      },
      {
        id: 1,
        name: '已售罄'
      },
    ],
    productNum: '', //筛选库存数量
    productNumList: [{
        id: 1,
        name: '0-50'
      },
      {
        id: 2,
        name: '51-99'
      },
      {
        id: 3,
        name: '大于100'
      },
    ],
    ipx: '',
    hidden: true,
    value: '',
    isEnd: false, //是否到底
    pageNumber: 1,
    sort: 'asc',
    orgSeq: '',
    inventory: 0,
    codeval:'',
    arr: [], //标签数组：用来存储选中的值product
    productTypeXg:0, //限购
    timeProduct:0, //定时任务商品
    isBuyLimit:9,//是否限购商品
    isTiming:9,//是否是定时任务
    shwShare:false,
    infor:{},
    width:307,
    height:534,
    catShopUrl: '', //名片海报
    imgUrl: common.imgUrl,
    isDisable: false,//防止多次点击
    cardPic:'', //背景图
    fontColor:'',//背景色
    swiperIndex:'',
    currents:0
  },
    // 跳转问题详情
    detile:function(){
      wx.navigateTo({
        url: '/pages/myCenter/problemDetil/problemDetil?code='+2+'&type='+1,
      })
    },
  // 关闭蒙版
  closeMask(){
    this.setData({
      shwShare:false
    })
  },
  // 产品分享
  productShare(e){  
    this.getWxCode(this.data.allproduct[e.currentTarget.dataset.index].goodsId)//获取小程序码
    this.setData({
      shwShare:true, 
      infor:this.data.allproduct[e.currentTarget.dataset.index],
      swiperIndex:e.currentTarget.dataset.index
    })
  },
  // swiper事件
  swiperChange(e) {
    this.setData({ 
      swiperIndex:e.detail.current
    })
    this.getWxCode(this.data.allproduct[e.detail.current].goodsId)//获取小程序码
  },
   // 获取基本信息
   getInfo: function(e) { 
    let data = {
      userId: app.globalData.userId,
      orgSeq: app.globalData.orgSeq
    }
    common.requestAjax('/api/user-service/v1/foreign/getUserAndStoreInfo', 'GET', data).then(res => {
      this.setData({
        stroeInfo: res.data.storeInfoDTO,
        userInfo: res.data.userInfoDTO,
      })
      this.queryGoodsUsaCard()//获得背景图和背景色
    }).catch(err => {
      console.log(err);
    })
  },
  // 获取小程序码
  getWxCode(goodsId,id) {
    let data = {
      page: "pages/shop/productDetil/index",
      type:2,//1活动分享   2商品分享 3 店铺分享
      sceneStr: goodsId + ',' + getApp().globalData.shopInfo.orgSeq + ',' + getApp().globalData.userId ,
      appid: getApp().globalData.appId,
      secret: getApp().globalData.wx_code,
      width: 300,
      orgSeq: getApp().globalData.shopInfo.orgSeq,
      userId: getApp().globalData.userId,
      phone:this.data.userInfo.tel
    }
    common.requestAjax('/api/file-service/v1/share/appletCode', 'POST', data).then(res => {
      if (res.data.code) {
        let wxCode = res.data.url.replace(":443", '');
        this.setData({
          wxCode,
        })
        if(id == 2){ 
          wx.previewImage({
            urls: [this.data.wxCode],
            complete: (res) => {},
            current: this.data.wxCode,
            fail: (res) => {},
            success: (res) => {},
          }) 
        }
      }
    }).catch(err => {
      console.log(err);
    })
  },
  //获得背景图和背景色
  queryGoodsUsaCard(){
    let data = {  
    }
    common.requestAjax('/api/user-service/v1/StoreCard/queryGoodsUsaCard', 'get', data).then(res => {
      if (res.data.code == 1) {  
        this.setData({ 
          cardPic:res.data.result.cardPic || '', //背景图
          fontColor:res.data.result.fontColor || '',//背景色
        })
      }
    }).catch(err => {
      console.log(err);
    })
  },
  //  限购商品类型
  productTypeXg:function(e){
    if(e.currentTarget.dataset.producttypexg==0){
      this.setData({
        productTypeXg:1,
        isBuyLimit:1
      })
    }else{
      this.setData({
        productTypeXg:0,
        isBuyLimit:9
      })
    }
  },
  // 限购商品定时任务
  timeProduct:function(e){
    if(e.currentTarget.dataset.timeproduct==0){
      this.setData({
        timeProduct:1,
        isTiming:1
      })
    }else{
      this.setData({
        timeProduct:0,
        isTiming:9
      })
    }
  },
  // 库存量筛选
  setInventory: function(e) {
    if(this.data.productType==3){
      this.setData({
        selType:3
      })
    }
    let opactive = '';
    let sort = 'asc'
    if (this.data.opactive == 4) {
      opactive = 5;
      sort = 'desc'
    } else {
      opactive = 4;
      sort = 'asc'
    }
    if (e.currentTarget.dataset.inventory == 0) {
      this.setData({
        inventory: 1
      })
    } else {
      this.setData({
        inventory: 0
      })
    }
    var that = this;
    that.setData({
      opactive: opactive,
      sort: sort,
    });
    that.getProductList(1, 1);
  },
  selType: function(e) {
    var that = this;
    that.setData({
      selType: e.currentTarget.dataset.type,
      productType: e.currentTarget.dataset.type,
      opactive: 4,
      sort : 'asc',
      value: '',
      product: null,
      productType: '',
      productNum: '',
      qRCodeMsg: ''
    });
    that.getProductList(1, 1)
  },
  // 跳转修改库存
  todetial: function(e) { 
    let item = JSON.stringify(e.currentTarget.dataset.item)
    wx.navigateTo({
      url: '/pages/inventoryMgt/editInventory/editInventory?jsonStr=' + item,
    }) 
  },
  submit: function() {
    this.setData({
      showModal: true
    })
  },
  go: function() {
    this.setData({
      showModal: false
    })
  }, 
  productType: function(e) {
    let productType = e.currentTarget.dataset.producttype;
    if (this.data.productType == productType) {
      this.setData({
        productType: '',
        selType: productType
      })
    } else {
      this.setData({
        productType: productType,
        selType: productType
      })
    }
  },
  productNum: function(e) {
    let productNum = e.currentTarget.dataset.productnum;
    if (this.data.productNum == productNum) {
      this.setData({
        productNum: ''
      })
    } else {
      this.setData({
        productNum: productNum
      })
    }
  },
  showMask: function(e) {
    this.setData({
      hidden: false, 
    })
  },
  hideMask: function(e) {
    if (e.currentTarget.dataset.no == 0) {
      let productList = this.data.productList;
      productList.forEach(item => {
        item.selected = false
      })
      this.setData({
        productList: productList,
        product: [],
        productType: '',
        productNum: '',
        selType: 9,
        productTypeXg:0, //限购
        timeProduct:0, //定时任务商品
        isBuyLimit:9,//限购入参
        isTiming:9//定时任务商品入参
      })
    } else {
      if (!this.data.productType && !this.data.productNum ){
        this.setData({
          hidden: true,
          codeval: '',
          selType:9
        });
      }
      this.setData({
        hidden: true,
        codeval:''
      });
      this.getProductList(1, 1)
    }
  },
// 点击商品系列分类
  product: function (e) {
   // 多选
    var that = this
    let index = e.currentTarget.dataset.index;//下标
    let value = e.currentTarget.dataset.product;//id
    let items = that.data.productList;
    let arr = that.data.arr;
    let val = items[index].selected; //点击前的值
    items[index].selected = !val;
    if(items[index].selected == true ){  //true 数组拼接  
      arr.push(value);
    }else{  //false删除该元素
      Array.prototype.remove=function(value){
        var len = this.length;
        for(var i=0,n=0;i<len;i++){//把出了要删除的元素赋值给新数组
          if(this[i]!=value){
          this[n++]=this[i];
          }else{
            console.log(i);//测试所用
          }
        }
        this.length = n;
        }; 
        this.data.product.remove(value); 
    }
    that.setData({
      productList: items,
      arr: arr,
      product: arr
    })
    
  },
  // 商品分类
  getTypeList: function() {
    let data = {
    }
    common.requestAjax('/api/goods-service/v1/goods/queryAllShopGoodsType', 'POST', data).then(res => {
      // /api/goods-service/v1/goods/queryALlShopGoodsType  最新获取商品系列分类接口
      // /api/goods-service/v1/goods/queryShopGoodsType 旧的获取商品系列分类接口
      if (res.data.code == 1) {
        let productList = res.data.records;
        productList.forEach(item => {
          item.selected = ''
        })
        this.setData({
          productList: productList
        })
      }
    }).catch(err => {
      console.log(err);
    })
  },
  ewm: function (e) {
    var _this = this;
    wx.scanCode({ //扫描API
      success: function (res) {
        _this.setData({
          value:res.result,
          codeval: res.result,
        })
        _this.getProductList(1,1);
      }
    })
  },
  // 获取输入框内容
  getval: function(e) {
    this.setData({
      value: e.detail.value
    })
    this.getProductList(1, 1)
  },
  onPullDownRefresh: function() {
    //清空搜索框
    this.setData({
      value: '',
      pageNumber: 1,
      isEnd: false
    })
    this.getProductList(1, 1)
    setTimeout(() => {
      wx.stopPullDownRefresh();
    }, 1200)
  },
  onReachBottom: function() {
    if (!this.data.isEnd) {
      let pageNumber = this.data.pageNumber;
      pageNumber += 1;
      this.getProductList(pageNumber, 2)
      wx.showLoading({
        title: '正在加载中...',
      })
      this.setData({
        pageNumber
      })
    }
  },
  // 商品列表
  getProductList: function(page, type) { 
    wx.showLoading({
      title: '加载中',
      icon:"none"
    })
    let data = {
      size: 10, //当前页长度
      current: page, //当前查询哪一页 
      condition: {
        orgSeq: this.data.orgSeq,
        keyword: this.data.value, //关键字 外部系统码 or 商品名字 or 国际条码 模糊查询
        goodsTypeId: this.data.product, //商品类型id
        stockStatus: this.data.selType, //库存状态 1 售罄 2 紧张 3 充足  9全部
        stockAmountStatus: this.data.productNum, //库存最小值
        sort: this.data.sort,
        isBuyLimit: this.data.isBuyLimit, //是否限购商品
        isTiming: this.data.isTiming, //是定时任务商品 
      }
    }
    common.requestAjax('/api/trade-service/v1/mystock/querygoodByObscure', 'POST', data).then(res => {
      if (res.data.code == 1) {
        wx.hideLoading()
        let arraylist = this.data.allproduct || [];
        let isEnd = this.data.isEnd;
        if (type == 1) {
          //下拉刷新  productList:res.data.records
          arraylist = res.data.records;
          isEnd = false;
        } else if (type == 2) {
          //上拉加载
          arraylist = arraylist.concat(res.data.records);
          if (res.data.records.length == 0) {
            //最后一行没数据 到底了
            isEnd = true;
          }
          setTimeout(() => {
            wx.hideLoading()
          }, 500)
        } 
        if (this.data.productType==3){
          this.setData({
              selType:9
          })
        }
        this.setData({
          allproduct: arraylist, 
          isEnd,
        });
      }
    }).catch(err => {
      wx.hideLoading()
    })
  }, 
  onLoad: function(options) {
    let orgSeq = app.globalData.orgSeq;
    let ipx = app.globalData.isIphoneX;
    this.setData({
      ipx: ipx,
      orgSeq: orgSeq
    })
    // 商品分类
    this.setData({
      value: this.data.codeval
    })
    this.getProductList(1, 1)
    this.getTypeList(); 
    this.getInfo();//店铺基本信息
  }, 
  // 绘制商品名片
  canvasKapian(e) {  
    this.getWxCode(this.data.allproduct[this.data.swiperIndex].goodsId)//获取小程序码
    this.setData({ 
      infor:this.data.allproduct[this.data.swiperIndex], 
    })
    wx.getSetting({
      success: res => {
        console.log(res);
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success: res => {
              this.canvasClick();
            },
            fail: err => {
              wx.showModal({
                title: "提示",
                content: '图片保存失败，您需要开启相册权限并且重新保存,是否开启?',
                success: res => {
                  if (res.confirm) {
                    wx.openSetting({
                      success: (res) => {
                        if (res.authSetting['scope.writePhotosAlbum']) {
                          this.canvasClick();
                        } else {
                          wx.showToast({
                            title: '获取权限失败,无法使用保存图片或视频到您的相册',
                            icon: 'none'
                          })
                        }
                      },
                    })
                  }
                }
              })
            }
          })
        } else {
          this.canvasClick();
        }
      }
    })
  },
  canvasClick() {
    this.setData({
      isDisable: true
    })
    wx.showLoading({
      title: '名片生成中...',
    })
    let goodsPicUrl = (this.data.infor.goodsPicUrl || this.data.infor.goodsPic || this.data.infor.url).replace(":443", ''); 
    console.log(goodsPicUrl)
    let cardPic = this.data.cardPic.replace(":443",'');
    let image1 = this.localImge(goodsPicUrl);
    let image2 = this.localImge(this.data.wxCode);
    let arr = []
    if(cardPic == ""){
      arr = [image1, image2]
    }else{
      let image3 = this.localImge(cardPic);
      arr = [image1, image2, image3]
    }
    Promise.all(arr).then(res => {
      console.log(res); 
      let goodsPicUrl = res[0];
      let wxCode1 = res[1];
      let cardPic1 =  res[2];
      let top = 30;
      let left = 35
      const ctx = wx.createCanvasContext("shareKapian");
      ctx.setFillStyle("#ffffff");//填充颜色
      ctx.fillRect(0, 0, this.data.width, this.data.height);   //画布大小 
      if(cardPic == ''){
      }else{ // 背景图
        ctx.drawImage(cardPic1 || '', 0, 0, this.data.width, this.data.height);
      }
      // 商品图片   img,x,y,width,height 236
      ctx.drawImage(goodsPicUrl, left, top, 236, 315);
      // 商品名字
      ctx.setFontSize(16);
      ctx.font = 'bold'; 
      ctx.fillStyle= this.data.fontColor || "#000000";
      ctx.fillText(this.data.infor.goodsName || this.data.infor.name || '', left, 380);
      // whetherMemberPrice 1是有会员价 0没有会员价 
      if(this.data.infor.whetherMemberPrice == 1){//会员价
        ctx.setFontSize(12); 
        ctx.fillStyle=this.data.fontColor || "#666666";
        ctx.fillText("会员价", left, 400);
        ctx.fillStyle="#fea60f";
        ctx.fillText(this.data.infor.memberPrice || '', left + 40, 400);
        ctx.fillStyle=this.data.fontColor || "#666666";
        ctx.fillText("建议零售价", left + 120, 400);
        ctx.fillStyle="#fea60f";
        ctx.fillText(this.data.infor.salePrice || '', left + 180, 400);
      }else{ // 没有会员价
        ctx.setFontSize(12); 
        ctx.fillStyle=this.data.fontColor || "#666666";
        ctx.fillText("建议零售价", left, 400);
        ctx.fillStyle="#fea60f";
        ctx.fillText(this.data.infor.salePrice || '', left + 60, 400);
      }
      // 店铺名字
      ctx.setFontSize(15);
      ctx.font = 'bold'; 
      ctx.fillStyle=this.data.fontColor || "#333333";
      ctx.fillText(this.data.stroeInfo.storeName || '', left, 440);
      // 店员图标
      ctx.drawImage('/images/icon/icon-member.png', left, 460, 10,10);
      // 店主||店长||店员和名字
      ctx.setFontSize(12); 
      ctx.fillStyle=this.data.fontColor || "#333333";
      let  member = ''
      if(this.data.userInfo.userType == 4){
        member = '店主'
      }else  if(this.data.userInfo.userType == 5){
        member = '店长'
      }else  if(this.data.userInfo.userType == 6){
        member = '店员'
      } 
      ctx.fillText(member + '：' + this.data.userInfo.realName || '', left+20, 470);
      // 电话图标
      ctx.drawImage('/images/icon/icon-tel.png', left, 490, 10,10);
      // 电话
      ctx.setFontSize(12); 
      ctx.fillStyle=this.data.fontColor || "#333333"; 
      ctx.fillText('电话：' + this.data.userInfo.tel || '', left+20, 500);
      // 二维码 
      this.circleImg(ctx, wxCode1, 210,425,22)  
      ctx.setFontSize(9); 
      // 识别小程序码
      ctx.setFontSize(9); 
      ctx.fillStyle=this.data.fontColor || "#666666"; 
      ctx.fillText('识别小程序码', 200, 484);
      // 提示进入详情页 
      ctx.setFontSize(9); 
      ctx.fillStyle=this.data.fontColor || "#666666"; 
      ctx.fillText('进入该店的商品详情页', 180, 499);

      ctx.save();
      ctx.draw(false, () => {
        wx.canvasToTempFilePath({
          canvasId: "shareKapian",
          success: res => {
            console.log('成功', res.tempFilePath)
            wx.hideLoading(); 
            this.setData({
              catShopUrl: res.tempFilePath
            });
            this.downFn();
          },
          fail: err => {
            console.log('生成失败', err);
          }
        });
      });
    }).catch(err => {
      console.log(err);
      wx.hideLoading();
      wx.showToast({
        title: '图片加载失败,请返回重试',
        icon: 'none'
      })
    })
  },
  //生成本地图片
  localImge: function (src) {
    console.log('src', src);
    return new Promise(function (resolve, reject) {
      wx.downloadFile({
        url: src,
        success: function (res) {
          resolve(res.tempFilePath);
        },
        fail: err => {
          reject(err)
        }
      });
    });
  },
  //保存图片
  downFn() {
    let imgurl = '';
    wx.showLoading({
      title: '保存中...',
    })
    imgurl = this.data.catShopUrl;
    wx.saveImageToPhotosAlbum({
      filePath: imgurl,
      success: res => {
        wx.hideLoading()
        wx.showToast({
          title: "保存成功，从相册中分享到朋友圈吧",
          icon: "none",
          duration: 4000
        });
        this.setData({
          isDisable: false
        })
        this.addNum();  //统计次数
      },
      fail: function (err) {
        this.setData({
          isDisable: false
        })
        console.log(err)
        if (err.errMsg === "saveImageToPhotosAlbum:fail:auth denied" || err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {  
          wx.hideLoading();
          wx.showModal({
            title: "提示",
            content: '图片保存失败，您需要开启相册权限并且重新保存,是否开启?',
            success: res => {
              if (res.confirm) {
                wx.openSetting({
                  complete: (res) => {
                    console.log(res);
                  },
                })
              }
            }
          })
        }
      }
    });
  },
  addNum:function(){ 
    //type 1 活动名片 2商品名片 3店铺名片
    common.requestAjax('/api/user-service/v1/storeDownloadCount/addCardAmount?orgSeq='+getApp().globalData.shopInfo.orgSeq+'&type='+2, 'POST').then(res => {
    }).catch(err => {
      console.log(err);
    })
  },
  // 圆形图片
  circleImg: function (ctx, img, x, y, r) {
    ctx.save()
    ctx.beginPath()
    var d = 2 * r;
    var cx = x + r;
    var cy = y + r;
    ctx.arc(cx, cy, r, 0, 2 * Math.PI);
    ctx.clip();
    ctx.drawImage(img, x, y, d, d);
    ctx.restore()
  },
  // 点击放大
  prewImage(e) { 
    this.getWxCode(this.data.allproduct[this.data.swiperIndex].goodsId,2)//获取小程序码
    // console.log(this.data.wxCode)
    // wx.previewImage({
    //   urls: [this.data.wxCode],
    //   complete: (res) => {},
    //   current: this.data.wxCode,
    //   fail: (res) => {},
    //   success: (res) => {},
    // })
  },
})
